<template>
  <a-modal
    title="新增海报"
    :visible="visible"
    :maskClosable="false"
    :destroyOnClose="true"
    :keyboard="false"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    width="800px"
    @cancel="handleCancel"
  >
    <a-form-model
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 18 }"
      :model="formData"
      :preserve="false"
      :rules="rules"
      ref="ruleForm"
    >
      <a-form-model-item label="海报名称" prop="name">
        <a-input
          style="width: 300px"
          v-model="formData.name"
          :maxLength="18"
          :disabled="operation == 'check'"
          placeholder="输入海报名称2-18个汉字"
        />
      </a-form-model-item>
      <a-form-model-item label="选择分类">
        <a-select
          style="width: 200px"
          :value="firstCategory"
          :options="firstCategoryList"
          :disabled="operation == 'check'"
          @change="firstCategoryChange"
          placeholder="选择一级分类"
        >
        </a-select>
        <a-select
          v-show="secondCategoryOptions.length > 0 || (posterInfo.secondPosterCategoryName && operation != 'add')"
          style="width: 200px"
          :disabled="operation == 'check'"
          :value="secondCategory"
          :options="secondCategoryOptions"
          @change="secondCategoryChange"
          placeholder="选择二级分类"
        >
        </a-select>
      </a-form-model-item>
      <a-form-model-item label="上传海报">
        <div>
          <upload-image
            v-model="formData.imgsUrl"
            ref="uploadImage"
            :beforeUploadFun="beforeUploadFun"
            :disabled="operation == 'check'"
          >
          </upload-image>
          <div :style="{ fontSize: '10px' }">注：宽度大于等于375像素，高度大于等于350像素</div>
        </div>
      </a-form-model-item>
      <a-form-model-item label="是否关联产品">
        <a-radio-group v-model="isRelatedProducts" :disabled="operation == 'check'">
          <a-radio :value="1">
            是<a-button
              v-if="isRelatedProducts == 1"
              @click="addProduct"
              type="link"
              :disabled="operation == 'check'"
              :style="{ padding: '0 10px' }"
              >添加产品</a-button
            >
          </a-radio>
          <a-radio :value="2"> 否 </a-radio>
        </a-radio-group>
        <table
          class="form-table"
          style="width: 450px"
          v-if="products.length > 0"
        >
          <thead>
            <tr>
              <th>名称</th>
              <th>类型</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(product, index) in products" :key="index">
              <td>
                <div class="product_name">{{ product.productName }}</div>
              </td>
              <td>{{ product.productType | filterProType }}</td>
              <td>
                <a-button
                  type="link"
                  :disabled="operation == 'check'"
                  @click="delChooseGoods(index)"
                  >删除</a-button
                >
              </td>
            </tr>
          </tbody>
        </table>
      </a-form-model-item>
      <a-form-model-item label="分享码位置">
        <a-space>
          分享码X轴：<a-input-number
            v-model="formData.shareCodeXAxis"
            :min="0"
            :max="maxXPostion"
            :disabled="operation == 'check'"
          />px
          <span :style="{ fontSize: '10px' }"
            >注：填写0-{{maxXPostion}}的整数，数字越大越靠右</span
          >
        </a-space>
        <a-space>
          分享码Y轴：<a-input-number
            v-model="formData.shareCodeYAxis"
            :min="0"
            :max="maxYPostion"
            :disabled="operation == 'check'"
          />px
          <span :style="{ fontSize: '10px' }"
            >注：填写0-{{maxYPostion}}的整数，数字越大越靠上</span
          >
        </a-space>
      </a-form-model-item>
      <a-form-model-item label="排序">
        <a-input-number
          style="width: 220px"
          v-model="formData.sort"
          :disabled="operation == 'check'"
          placeholder="填写整数，数字越大越靠后"
        />
      </a-form-model-item>
      <a-form-model-item label="有效期">
        <a-date-picker
          v-model="formData.edStart"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          show-time
          type="date"
          :disabled="operation == 'check'"
          placeholder="请选择日期"
        />
        <span :style="{ margin: '0 .1rem' }">至</span>
        <a-date-picker
          v-model="formData.edEnd"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          show-time
          type="date"
          :disabled="operation == 'check'"
          placeholder="请选择日期"
        />
      </a-form-model-item>
      <a-form-model-item label="分享话术" prop="shareScirpt">
        <a-textarea 
          placeholder="请输入分享话术" 
          :style="{width: '400px', minHeight: '100px'}"
          :disabled="operation == 'check'" 
          v-model="formData.shareScirpt"
          :maxLength="500" 
          auto-size />
          <!-- <a-col :offset="0">
            <SimplifyTinymce v-model="formData.shareScirpt"></SimplifyTinymce>
          </a-col> -->
      </a-form-model-item>
      <a-form-model-item label="是否启用">
        <a-switch :defaultChecked="formData.isUsed == 1" @change="onEnableChange" :disabled="operation == 'check'" />
      </a-form-model-item>
    </a-form-model>
    <template slot="footer">
      <a-space>
        <a-button type="primary" @click="handlePreview"> 预览 </a-button>
        <a-button type="primary" :disabled="operation == 'check'" :loading="isConfirm" @click="handleOk"
          >确定</a-button
        >
        <a-button key="back" @click="handleCancel">取消</a-button>
      </a-space>
    </template>
    <AddProduct :visible="isAddProduct" @getProductList="getProductList" @cancel="isAddProduct = false"></AddProduct>
    <PosterPreview :visible="isPreview" :posterData="formData" @cancel="isPreview = false"></PosterPreview>
  </a-modal>
</template>
<script>
import AddProduct from './AddProduct';
import PosterPreview from './PosterPreview';
import SimplifyTinymce from './SimplifyTinymce';
export default {
  name: "AddPoster",
  props: {
    operation: {
      type: String,
      default: "add"
    },
    firstCategoryList: {
      type: Array,
      default: () => {
        return []
      },
      required: true
    },
    secondCategoryInfo: {
      type: Object,
      default: () => {
        return {}
      }
    },
    posterInfo: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  components: {
    AddProduct,
    PosterPreview,
    SimplifyTinymce
  },
  filters: {
    filterProType(type) {
      switch(+type) {
        case 1:
          return '图库'
        case 2:
          return '案例'
        case 3:
          return '视频'
      }
    }
  },
  watch: {
    posterInfo: {
      handler(val) {
        if(this.operation != 'add' && this.operation != 'preview') { //回显数据
          this.getEchoFormInfo(val)
        }
      },
      deep: true
    },
    operation: {
      handler(val) {
        if(val == 'add') {
          this.initFormData();
        }
      },
      immediate: true
    },
    "formData.imgsUrl"(val) {
      if(val === "") {
        this.maxXPostion = this.maxYPostion = 0;
      }
    },
    visible(val) {
      if(val === false) {
        this.initFormData();
      }
    }
  },
  data() {
    return {
      confirmLoading: false,
      visible: false,
      formData: {
        name: "", //海报名称
        imgsUrl: "", //海报图片地址
        shareCodeXAxis: "", //分享码X轴
        shareCodeYAxis: "", //分享码Y轴
        sort: "", //排序
        edStart: "", //有效期开始时间
        edEnd: "", //有效期结束时间
        shareScirpt: "",//分享话术
        isUsed: "1" //是否启用1、启用，0不启用
      },
      firstCategory: undefined,//一级分类
      secondCategory: undefined, //二级分类
      secondCategoryOptions: [],//二级分类选项列表
      products: [], //关联产品 项{productType	产品类型 1图库，2案例，3视频，4实拍图 productId	产品id}
      isRelatedProducts: 2, //1是 2否
      isConfirm: false,
      rules: {
        name: [{ required: true, message:'请输入海报名称', min:2, max: 18 }],
        shareScirpt: [{ required: true, message:'请输入分享话术'},{ min:6, max: 500, message:'输入分享话术6-500个汉字'}]
      },
      isPreview: false,
      isAddProduct: false,
      maxXPostion: 0, //最大可设置X轴位置
      maxYPostion: 0 //最大可设置Y轴位置
    };
  },
  methods: {
    getEchoFormInfo(posterInfo) { //回显数据
      let keys = Object.keys(this.formData);
      keys.forEach(key => {
        this.formData[key] = posterInfo[key];
      });
      if(this.operation != 'add') { //编辑和查看 根据分类名称去筛选
        this.beforeUploadFun(this.formData.imgsUrl)
        this.firstCategory = this.firstCategoryList.find(item => {
          return item.label == this.posterInfo.firstPosterCategoryName
        })?.value;
        if(this.posterInfo.secondPosterCategoryName) {
          this.secondCategoryOptions = this.secondCategoryInfo[this.firstCategory].map(item => { //获取当前选择一级分类下二级分类
            return {
              label: item.name,
              value: item.id
            }
          })
          this.secondCategory = this.secondCategoryOptions.find(item => {
            return item.label == this.posterInfo.secondPosterCategoryName
          })?.value;
        }else {
          this.secondCategoryOptions = []
        }
        if(posterInfo.products && posterInfo.products.length > 0) {
          this.isRelatedProducts = 1;
          this.products = posterInfo.products;
        }
      }
    },
    //一级分类change
    firstCategoryChange(value) {
      this.firstCategory = value;
      this.secondCategory = undefined;
      if(!this.secondCategoryInfo[value] || this.secondCategoryInfo[value].length == 0) return this.secondCategoryOptions = [];
      this.secondCategoryOptions = this.secondCategoryInfo[value].map(item => { //获取当前选择一级分类下二级分类
        return {
          label: item.name,
          value: item.id
        }
      });
    },
    // 二级分类change
    secondCategoryChange(value) {
      this.secondCategory = value;
    },
    onEnableChange(val) {
      this.formData.isUsed = val ? '1' : '0';
    },
    delChooseGoods(index) {
      this.products.splice(index, 1)
    },
    getProductList(list) {
      let arr = list.concat(this.products);
      let hash = {};
      this.products = arr.reduce((item, next) => {
        hash[next.productId] ? '' : (hash[next.productId] = true && item.push(next));
        return item
      }, [])
      this.isAddProduct = false;
    },
    // 图片上传之前处理
    beforeUploadFun(file) {
      return new Promise((resolve, reject) => {
        let img = new Image();
        if(file instanceof File) {
          let reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = () => {
            img.src = reader.result;
          }
        }else {
          img.src = file;
        }
        img.onload = () => {
          // 限制宽度750像素，高度大于等于160像素
          if(img.width < 375 || img.height < 350) {
            this.$message.error("请上传宽度大于等于375像素，高度大于等于350像素的海报");
            this.formData.imgsUrl = '';
            this.$refs.uploadImage.files = [];
            reject()
          }else {
            resolve()
            // 符合条件 计算分享二维码最大可设置位置值
            this.maxXPostion = img.width - 160;
            this.maxYPostion = img.height - 160;
          }
        }
      })
    },
    // 校验必填项
    checkData() {
      if(!this.formData.name) {
        this.$message.error('请输入海报名称');
        return false;
      }
      if(!this.formData.imgsUrl) {
        this.$message.error('请上传海报图片');
        return false;
      }
      if(!this.firstCategory) {
        this.$message.error('请选择一级分类');
        return false;
      }
      if(this.secondCategoryOptions.length > 0 && !this.secondCategory) {
        this.$message.error('请选择二级分类');
        return false;
      }
      if(!this.formData.shareCodeXAxis && this.formData.shareCodeXAxis !== 0) {
        this.$message.error('请输入分享码X轴');
        return false;
      }
      if(!this.formData.shareCodeYAxis && this.formData.shareCodeYAxis !== 0) {
        this.$message.error('请输入分享码Y轴');
        return false;
      }
      if(!this.formData.sort) {
        this.$message.error('请输入排序');
        return false;
      }
      if(!this.formData.edStart) {
        this.$message.error('请输入有效期开始时间');
        return false;
      }
      if(!this.formData.edEnd) {
        this.$message.error('请输入有效期结束时间');
        return false;
      }
      if(!this.formData.shareScirpt) {
        this.$message.error('请输入分享话术');
        return false;
      }
      return true;
    },
    // 重置数据  不知道为啥destroyOnClose 没起效果
    initFormData() {
      this.formData = {
        name: "", //海报名称
        imgsUrl: "", //海报图片地址
        shareCodeXAxis: "", //分享码X轴
        shareCodeYAxis: "", //分享码Y轴
        sort: "", //排序
        edStart: "", //有效期开始时间
        edEnd: "", //有效期结束时间
        shareScirpt: "",//分享话术
        isUsed: "1" //是否启用1、启用，0不启用
      },
      this.products = [];
      this.firstCategory = undefined;//一级分类
      this.secondCategory = undefined; //二级分类
      this.isRelatedProducts = 2
    },
    // 预览
    handlePreview() {
      if(!this.checkData()) return;
      this.isPreview = true;
    },
    handleOk() {
      if(!this.checkData()) return;
      this.isConfirm = true;
      this.$post(`goldenhome/gh/poster_/admin/poster/${this.operation}`, {
        ...this.formData,
        id: this.operation == 'update' ? this.posterInfo.id : undefined,
        posterCategoryId: this.secondCategory || this.firstCategory, //分类id 选了二级分类就传二级分类 没有二级分类传一级分类的
        products: this.products //是否启用1、启用，0不启用
      }).then(res => {
        if (res && res.returnCode == 1000) {
          this.isConfirm = false;
          this.$message.success('添加成功');
          this.initFormData();
          this.$emit("confirm")
        }
      })
    },
    handleCancel() {
      this.initFormData()
      this.$emit("cancel");
    },
    addProduct() {
      if(this.operation == 'check') return;
      this.isAddProduct = true;
    }
  },
};
</script>
